package de.gameduell.framework.game.billard.view {
	import fl.transitions.TweenEvent;
	import fl.transitions.easing.None;
	
	import de.gameduell.framework.application.protocol.MultiplayerProtocol;
	import de.gameduell.framework.game.billard.controller.IBillardController;
	import de.gameduell.framework.gui.animation.PositionTween;
	
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.geom.Point;	

	/**
	 * @author cbra
	 */
	public class BallTube {
		private var content:Sprite;
		private var positionSprites:Array;
		private var startPos:Point;
		private var balls:Array;
		private var animate:Boolean;
		private var container:Sprite;
		private var controller:IBillardController;

		public function BallTube(aContent:Sprite,aController:IBillardController,aAnimate:Boolean) {
			content = aContent;
//			_pocketedBallNum = 0;
			animate = aAnimate;
			balls  = new Array();
			controller = aController;
			controller.addEventListener(MultiplayerProtocol.GO, onGo);
			var startPosPlaceHolder:Sprite = content.getChildByName("startPos") as Sprite;
			startPos = new Point(startPosPlaceHolder.x,startPosPlaceHolder.y);
			positionSprites = new Array();
		
			container = content.getChildByName("ballContainer") as Sprite;
			for(var i:int= 0; i< 15;i++){
				var placeHolder:Sprite = content.getChildByName("pocketed_ball_"+i) as Sprite;
				positionSprites.push(placeHolder);
			}
		}
		
		private function onGo(event:Event):void {
			clear();
		}

		public function set pocketedBalls(aBallList:Array):void {
			if(aBallList.length > balls.length) {
				for(var i:int = balls.length;i < aBallList.length;i++) {				
					var ballIndex:int = int(aBallList[i]);
					var ball:Ball3D = new Ball3D("ball_" + ballIndex, container);	
					var placeHolder:Sprite = Sprite(positionSprites[i]);
					balls.push(ball);
					if(animate) {
						var posTween:PositionTween = new PositionTween(ball, None.easeNone, startPos, new Point(placeHolder.x, placeHolder.y), 1.5, true);		
						posTween.addEventListener(TweenEvent.MOTION_CHANGE, ball.update);
						posTween.start();
					}else{
						ball.x = placeHolder.x;
						ball.y = placeHolder.y;
					}
				}	
//				_pocketedBallNum = aBallList.length;
			}
		}
		
		public function clear():void{
			for(var i:* in balls){
				container.removeChild(Ball3D(balls[i]).sprite);
			}
			balls.length = 0;
//			_pocketedBallNum = 0;
		}
	}
}
